<template>
  <div class="forgot-password-container">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <el-icon class="back-icon" @click="goBack"><ArrowLeft /></el-icon>
      <div class="page-title">{{ t('forgotPassword.title') }}</div>
      <div class="placeholder"></div>
    </div>

    <!-- 主体内容 -->
    <div class="forgot-password-content">
      <!-- 手机号输入框 -->
      <div class="form-item" :class="{ 'error': errors.phone }">
        <el-icon><Iphone /></el-icon>
        <input
          v-model="verifyForm.phone"
          :placeholder="t('forgotPassword.phonePlaceholder')"
          class="form-input"
          type="text"
          @blur="validateField('phone')"
          @input="clearError('phone')"
        />
      </div>
      <div v-if="errors.phone" class="error-message">{{ errors.phone }}</div>

      <!-- 图片验证码 -->
      <div class="form-item" :class="{ 'error': errors.imageCaptcha }">
        <el-icon><Picture /></el-icon>
        <div class="captcha-container">
          <input
            v-model="verifyForm.imageCaptcha"
            :placeholder="t('forgotPassword.imageCaptchaPlaceholder')"
            class="form-input"
            type="text"
            @blur="validateField('imageCaptcha')"
            @input="clearError('imageCaptcha')"
          />
          <div class="image-captcha" @click="refreshCaptcha">
            <img :src="captchaImage" alt="验证码" />
          </div>
        </div>
      </div>
      <div v-if="errors.imageCaptcha" class="error-message">{{ errors.imageCaptcha }}</div>

      <!-- 短信验证码 -->
      <div class="form-item" :class="{ 'error': errors.captcha }">
        <el-icon><Message /></el-icon>
        <div class="captcha-container">
          <input
            v-model="verifyForm.captcha"
            :placeholder="t('forgotPassword.captchaPlaceholder')"
            class="form-input"
            type="text"
            @blur="validateField('captcha')"
            @input="clearError('captcha')"
          />
          <button
            type="button"
            class="captcha-button"
            :disabled="captchaDisabled || !canSendSms"
            @click="handleGetCaptcha"
          >
            {{ captchaText }}
          </button>
        </div>
      </div>
      <div v-if="errors.captcha" class="error-message">{{ errors.captcha }}</div>

      <!-- 新密码输入框 -->
      <div class="form-item" :class="{ 'error': errors.newPassword }">
        <el-icon><Lock /></el-icon>
        <input
          v-model="resetForm.newPassword"
          type="password"
          :placeholder="t('forgotPassword.newPasswordPlaceholder')"
          class="form-input"
          @blur="validateField('newPassword')"
          @input="clearError('newPassword')"
        />
      </div>
      <div v-if="errors.newPassword" class="error-message">{{ errors.newPassword }}</div>

      <!-- 完成按钮 -->
      <button
        type="button"
        class="submit-button"
        :disabled="loading || hasErrors"
        @click="handleReset"
      >
        {{ loading ? t('forgotPassword.loading') : t('forgotPassword.complete') }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useCaptchaStore } from 'store';
import { ElMessage } from 'element-plus';
import { ArrowLeft, Iphone, Message, Lock, Picture } from '@element-plus/icons-vue';
import authService from '../../services/authService';

// 国际化
const { t } = useI18n();

// 路由
const router = useRouter();

// Store
const captchaStore = useCaptchaStore();

// 验证表单数据
const verifyForm = reactive({
  phone: '',
  imageCaptcha: '',
  captcha: ''
});

// 重置密码表单数据
const resetForm = reactive({
  newPassword: ''
});

// 错误信息
const errors = reactive({
  phone: '',
  imageCaptcha: '',
  captcha: '',
  newPassword: ''
});

// 加载状态
const loading = ref(false);

// 验证码图片
const captchaImage = ref('');

// 验证码相关
const captchaTime = ref(0);
const captchaDisabled = computed(() => captchaTime.value > 0);
const captchaText = computed(() => {
  return captchaTime.value > 0 
    ? `${captchaTime.value}s` 
    : t('forgotPassword.getCaptcha');
});

// 是否可以发送短信验证码
const canSendSms = computed(() => {
  return !errors.phone && !errors.imageCaptcha && verifyForm.phone && verifyForm.imageCaptcha;
});

// 计算属性：是否有错误
const hasErrors = computed(() => {
  return Object.values(errors).some(error => error !== '');
});

// 生命周期钩子
onMounted(() => {
  refreshCaptcha();
});

// 刷新验证码
const refreshCaptcha = () => {
  captchaImage.value = captchaStore.generateImageCaptcha();
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 清除特定字段的错误
const clearError = (field) => {
  errors[field] = '';
};

// 验证特定字段
const validateField = (field) => {
  switch (field) {
    case 'phone':
      validatePhone();
      break;
    case 'imageCaptcha':
      validateImageCaptcha();
      break;
    case 'captcha':
      validateCaptcha();
      break;
    case 'newPassword':
      validatePassword();
      break;
  }
};

// 验证所有字段
const validateAllFields = () => {
  validatePhone();
  validateImageCaptcha();
  validateCaptcha();
  validatePassword();
  
  return !hasErrors.value;
};

// 验证手机号
const validatePhone = () => {
  if (!verifyForm.phone) {
    errors.phone = t('forgotPassword.phoneRequired');
    return false;
  }
  if (!/^1[3-9]\d{9}$/.test(verifyForm.phone)) {
    errors.phone = t('forgotPassword.phoneFormat');
    return false;
  }
  errors.phone = '';
  return true;
};

// 验证图片验证码
const validateImageCaptcha = () => {
  if (!verifyForm.imageCaptcha) {
    errors.imageCaptcha = t('forgotPassword.imageCaptchaRequired');
    return false;
  }
  
  if (!captchaStore.verifyImageCaptcha(verifyForm.imageCaptcha)) {
    errors.imageCaptcha = t('forgotPassword.captchaError');
    return false;
  }
  
  errors.imageCaptcha = '';
  return true;
};

// 验证短信验证码
const validateCaptcha = () => {
  if (!verifyForm.captcha) {
    errors.captcha = t('forgotPassword.captchaRequired');
    return false;
  }
  
  if (verifyForm.captcha.length < 4 || verifyForm.captcha.length > 6) {
    errors.captcha = t('forgotPassword.captchaLength');
    return false;
  }
  
  errors.captcha = '';
  return true;
};

// 验证密码
const validatePassword = () => {
  if (!resetForm.newPassword) {
    errors.newPassword = t('forgotPassword.newPasswordRequired');
    return false;
  }
  if (resetForm.newPassword.length < 6 || resetForm.newPassword.length > 16) {
    errors.newPassword = t('forgotPassword.passwordLength');
    return false;
  }
  errors.newPassword = '';
  return true;
};

// 获取验证码
const handleGetCaptcha = async () => {
  // 验证手机号和图片验证码
  if (!validatePhone() || !validateImageCaptcha()) {
    return;
  }
  
  // 发送验证码
  await authService.sendSmsCode(verifyForm.phone,3);

  //倒计时
  captchaStore.startSmsCountdown(verifyForm.phone);
  captchaTime.value = 60;
  const timer = setInterval(() => {
    captchaTime.value--;
    if (captchaTime.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
  ElMessage.success(t('forgotPassword.captchaSent'));
};

// 重置密码
const handleReset = async () => {
  // 验证所有字段
  if (!validateAllFields()) {
    return;
  }
  
  loading.value = true;
  try {
    // 重置密码
    await authService.resetPasswordByPhone({
      phone: verifyForm.phone,
      type: 3,
      code: verifyForm.captcha,
      newPassword: resetForm.newPassword
    });
    
    setTimeout(() => {
      ElMessage.success(t('forgotPassword.resetSuccess'));
      router.push('/login');
    }, 1000);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped lang="scss">
.forgot-password-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 15px;
  background-color: #3a4a6d;
  color: white;
  position: relative;

  .back-icon {
    font-size: 20px;
    cursor: pointer;
  }

  .page-title {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    font-size: 18px;
    font-weight: 500;
  }

  .placeholder {
    width: 20px;
  }
}

.forgot-password-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  margin-top: 20px;
}

.form-item {
  display: flex;
  align-items: center;
  background-color: white;
  border-radius: 4px;
  margin-bottom: 5px;
  padding: 0 15px;
  height: 50px;
  border: 1px solid transparent;
  transition: all 0.3s;

  &.error {
    border-color: #f56c6c;
  }

  .el-icon {
    margin-right: 10px;
    color: #999;
  }

  .form-input {
    flex: 1;
    border: none;
    outline: none;
    height: 100%;
    width: 100%;
    font-size: 16px;
    background: transparent;
  }
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin: -2px 0 10px 15px;
  height: 18px;
}

.captcha-container {
  display: flex;
  flex: 1;
  gap: 10px;

  .form-input {
    flex: 1;
  }

  .captcha-button {
    width: 100px;
    height: 36px;
    padding: 0;
    font-size: 12px;
    background-color: #3a4a6d;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    
    &:disabled {
      opacity: 0.7;
      cursor: not-allowed;
    }
  }
  
  .image-captcha {
    width: 100px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 4px;
    }
  }
}

.submit-button {
  width: 100%;
  height: 44px;
  margin-top: 20px;
  border-radius: 4px;
  font-size: 16px;
  background-color: #3a4a6d;
  border: none;
}
</style>